package com.hltx.controller.user;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hltx.constants.PayConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.user.User;
import com.hltx.pojo.user.UserVipPay;
import com.hltx.pojo.user.VipConfigure;
import com.hltx.service.user.UserManager;
import com.hltx.service.user.UserPayManager;
import com.hltx.service.user.UserVipManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.DataUtil;
import com.hltx.util.DateUtil;
import com.hltx.util.ResultInfo;

/**
 * 用户controller
 * 
 * @author
 *
 */
@Controller
public class UserVipPayController extends BaseController {

	@Autowired
	private UserVipManager userVipService;

	@Resource(name = "userService")
	private UserManager userService;
	
	@Resource(name = "userPayService")
	private UserPayManager userPayService;
	
	/*@Autowired
	private VipBonusService vipBonusService;*/
	

	/**
	 * vip升级(余额充值VIP)
	 * testing
	 */
	@RequestMapping(value = "/myvip/balance_pay_vip", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> balancePayVip(UserVipPay uvp, HttpServletRequest request,
			HttpSession session) {
		this.logBefore(logger, "vip升级");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			User user = (User) session.getAttribute(
					"sessionUser");
			//参数的验证
			int res = validateParams(uvp, user, resMap);
			if(res == 0){
				//生成订单信息
				Map<String, Object> params = new HashMap<String, Object>();
				uvp.setPayMode(PayConstant.PAY_BALANCE);
				params.put("uvp", uvp);
				if(resMap.containsKey("isRelation")){
				params.put("isRelation", resMap.get("isRelation"));
				}
				ResultInfo resInfo = userPayService.cbalancePayVip(params);
				resMap.put("result", resInfo);
				
//				if(StringUtils.equals(resInfo.getState(), ResultInfo.SUCCESS)){		
//					//计算佣金
//					if(uvp.getTotalPrice().compareTo(BigDecimal.ZERO)>0){
//						User curUser = userService.getUserInfo(user.getLoginId());
//						vipBonusService.vipBonusTask(curUser, uvp.getTotalPrice());
//					}
//				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 参数验证
	 * @return
	 */
	public int validateParams(UserVipPay uvp, User user, Map<String, Object> resMap) throws Exception{
		//验证用户是否登录
		if(user == null){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "LOGIN_OUT", "用户未登录",null));
			return 1;
		}
		
		if(uvp == null){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "LOGIN_OUT", "参数错误",null));
			return 1;
		}
		
		//验证金额
		BigDecimal totalPrice = DataUtil.getBigDecimal(uvp.getTotalPrice());
		if(totalPrice.compareTo(BigDecimal.ZERO) <=0){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "金额有误",null));
			return 1;
		}
		
		//验证VIP等级
		user = userService.getUserInfo(user.getLoginId());
		int curLevel = CustomUtil.strToInt(user.getLevel());
		int toLevel = uvp.getLevel();
		
		if(toLevel <=0 || toLevel <= curLevel){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "VIP_LEVEL_ERROR", "VIP等级错误",null));
			return 1;
		}
		
		//验证VIP充值金额
		VipConfigure curVip = null,toVip = null;
		if(curLevel >0){
			curVip = userVipService.getVipByLevel(curLevel);
		}
		toVip = userVipService.getVipByLevel(toLevel);
		BigDecimal realTotalPrice = DataUtil.getBigDecimal(toVip.getPrice());
		BigDecimal returnPrice = DataUtil.getBigDecimal(toVip.getReturnPrice());
		int returnPoints = toVip.getReturnPoints();
		if(curVip != null){
			BigDecimal curPrice = DataUtil.getBigDecimal(curVip.getPrice());
			BigDecimal curReturnPrice = DataUtil.getBigDecimal(curVip.getReturnPrice());
			realTotalPrice = realTotalPrice.subtract(curPrice);
			returnPrice = returnPrice.subtract(curReturnPrice);
			returnPoints = returnPoints - curVip.getReturnPoints();
		}
		if(realTotalPrice.compareTo(totalPrice) != 0){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "PRICE_ERROR", "金额有误",null));
			return 1;
		}
		if(returnPrice.compareTo(BigDecimal.ZERO)<0){
			returnPrice = BigDecimal.ZERO;
		}
		if(returnPoints<0){
			returnPoints = 0;
		}
		
		//验证父级
//		String parentPhone = uvp.getParentPhone();
//		if(StringUtils.isNotEmpty(parentPhone)){
//			if(StringUtils.equals(user.getPhone(), parentPhone)){
//				resMap.put("result", this.initResult(ResultInfo.ERROR, "PARENT_ERROR", "上级用户不可以是自己",null));
//				return 1;
//			}
//			
//			User uParent = userVipService.getParentByUserName(parentPhone);
//			if(uParent == null){
//				resMap.put("result", this.initResult(ResultInfo.ERROR, "PARENT_NULL", "上级用户不存在",null));
//				return 1;
//			}
//			int level = CustomUtil.strToInt(uParent.getLevel());
//			if(level <= 0){
//				resMap.put("result", this.initResult(ResultInfo.ERROR, "PARENT_NOTVIP", "上级不是VIP用户",null));
//				return 1;
//			}
//			Map<String, Object> params = new HashMap<String, Object>();
//			params.put("userId", uParent.getId());
//			params.put("parentId", user.getId());
//			Map<String, Object> relation = userVipService.getUserRelationByUserId(params);
//			if(relation != null){
//				resMap.put("result", this.initResult(ResultInfo.ERROR, "CHILD_VIP", "上级用户不可以是自己的下级",null));
//				return 1;
//			}
//			uvp.setParentId(uParent.getId());
//			resMap.put("isRelation", "Y");
//
//	
//		}
		
		//封装参数
		uvp.setCurLevel(curLevel);
		uvp.setCodePre(DateUtil.getYear());
		uvp.setCodeSuf(CustomUtil.codeSuf(3, user.getId()));
		uvp.setReturnPoints(returnPoints);
		uvp.setReturnPrice(returnPrice);
		uvp.setTotalPrice(realTotalPrice);
		uvp.setUserId(user.getId());
		
		return 0;
	}
}
